<?php
/** Model 生成工具
 * 步骤
 * 1. 查看数据库配置是否正确
 * 2. 修改作者(author)
 * 3. DOS 进入该目录执行: >php model.php [模块名(注意大小写)] [表名] [模型名(注意大小写)] [应用程序名(注意大小写)]
 *    如: >php model.php Log sys_log System gm
 */

new my;

class my
{

    public $db;

    protected $_config = array(
        'dbhost'=>'localhost',
        'dbname'=>'test',
        'dbuser'=>'root',
        'dbpw'=>'123456',
    );

    protected $_author = 'MO <xiemaomao@iwgame.com>';

    protected $_files;

    protected $_model;

    protected $_module;

    protected $_table;

    protected $_data;

    public function __construct()
    {
        $this->_initFile();
        $this->_initDb();
        $this->createModel();
        //$this->createMapper();
        $this->createDbTable();
    }

    protected function _initFile()
    {
        global $argv;
        if (!isset($argv[1]) || !isset($argv[2]) || !isset($argv[3])) {
            print @"error ($argv[1]) ($argv[2]) ($argv[3]) \nphp model.php [name] [table] [module]";
            exit;
        }

        $this->_model  = $argv[1];
        $this->_table  = $argv[2];
        $this->_module = $argv[3];

        $this->_files['model'] = dirname(__FILE__) . "/../application/modules/{$argv[3]}/models/{$argv[1]}.php";
        $this->_files['mapper'] = dirname(__FILE__) . "/../application/modules/{$argv[3]}/models/{$argv[1]}Mapper.php";
        $this->_files['db-table'] = dirname(__FILE__) . "/../application/modules/{$argv[3]}/models/DbTable/{$argv[1]}.php";

        if (!file_exists("../application/modules/{$argv[3]}/models")) {
            mkdir("../application/modules/{$argv[3]}/models");
        }

        if (!file_exists("../application/modules/{$argv[3]}/models/DbTable")) {
            mkdir("../application/modules/{$argv[3]}/models/DbTable");
        }

        foreach ($this->_files as $f) {
            if (file_exists($f)) {
                rename($f, $f . time() . '.bak');
            }
        }
    }

    protected function _initDb()
    {
        $CONFIG = $this->_config;
        try {
            $this->db = new PDO('mysql:host=' . $CONFIG['dbhost'] . ';dbname=' . $CONFIG['dbname'] , $CONFIG['dbuser'], $CONFIG['dbpw']);
            $this->db->query('set names utf8');

            $query = $this->db->query("desc `$this->_table`");
            if (!$query) {
                echo implode('|', $this->db->errorInfo());
                exit;
            }

            $this->_data = $query->fetchAll();

        } catch (PDOException $e) {
            print "Error!: " . $e->getMessage() . "<br/>";
            die();
        }
    }

    public function createModel()
    {
        $class = ucfirst($this->_module) . '_Model_' . ucfirst($this->_model);

        $var = "\n    protected \$_data = array(\n";
        $doc = '';
        foreach($this->_data as $v) {
            $var .= "        '{$v[0]}' => null,\n";
            $ptype = strpos($v[1], 'int') !== false ? 'int' : 'string';
            $doc .= " * @property $ptype \${$v[0]} \n";
        }
        $var .= "    );\n";

        $func = "\n";
        foreach($this->_data as $v) {
            $v1 = preg_replace('/_([a-z])/e', 'strtoupper("$1")', $v[0]);
            $v2 = ucfirst($v1);

            $strtype = '';
            $ptype = 'string';
            if (strpos($v[1], 'int') !== false) {
                $ptype = 'int';
                $strtype = '(int)';
            }
            $func .= <<<EOT

    /**
     * @param $ptype \$value
     * @return $class
     */
    public function set$v2(\$value)
    {
        \$this->{$v[0]} = $strtype \$value;
        return \$this;
    }

    public function get$v2()
    {
        return \$this->{$v[0]};
    }

EOT;
}

        $content = <<<EOT
<?php
/**
 * $class
 *
 * @author $this->_author
 * @copyright Copyright (c) 2009 Green Shore (http://www.iwgame.com)
 * @version \$Id\$
 *
$doc * @method $class find()
 * @method $class fetchRow()
 * @method array fetchKeyPair fetchKeyPair($columns, $where, $order, $group, $limit, $offset)
 * @method array fetchColumn fetchColumn($columns, $where, $order, $group, $limit, $offset)
 * @method array fetchUnique fetchUnique($columns, $where, $order, $group, $limit, $offset)
 * @method array fetchGroup fetchGroup($columns, $where, $order, $group, $limit, $offset)
 */
class $class extends IG_Model
{
$var
$func
}
EOT;

        file_put_contents($this->_files['model'], $content);
    }

    public function createMapper()
    {

        $class = ucfirst($this->_module) . '_Model_' . ucfirst($this->_model) . 'Mapper';

        $content = <<<EOT
<?php
/**
 * $class
 *
 * @author $this->_author
 * @copyright Copyright (c) 2009 Green Shore (http://www.iwgame.com)
 * @version \$Id\$
 */
class $class extends IG_ModelMapper
{

}
EOT;

        file_put_contents($this->_files['mapper'], $content);
    }

    public function createDbTable()
    {
        $class = ucfirst($this->_module) . '_Model_DbTable_' . ucfirst($this->_model);
        $primary = array();
        foreach ($this->_data as $r) {
            if ($r['Key'] == 'PRI') {
                $primary[] = $r['Field'];
            }
        }

        if (count($primary) == 1) {
            $primary = $primary[0];
        }

        $primary = var_export($primary, true);

        $content = <<<EOT
<?php
/**
 * $class
 *
 * @author $this->_author
 * @copyright Copyright (c) 2009 Green Shore (http://www.iwgame.com)
 * @version \$Id\$
 */
class $class extends IG_Model_DbTable
{
    protected \$_name = '{$this->_table}';

    protected \$_primary = $primary;

}
EOT;

        file_put_contents($this->_files['db-table'], $content);
    }
}